package com.bobi.tfca.ui.login

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.navigation.NavOptions
import androidx.navigation.fragment.findNavController
import com.bobi.doublewillow.utils.SPUtil
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentLoginLayoutBinding
import com.bobi.tfca.model.LoginStatus
import com.bobi.tfca.network.response.MemberResponse
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MemberAPI
import com.bobi.tfca.network.client.AppCache
import com.bobi.tfca.util.LogUtil
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * @Author: Setruth
 * @Date: 2023/3/26 11:04
 */
class LoginFragment : BaseFragment<FragmentLoginLayoutBinding, LoginFragmentViewModel>(
    FragmentLoginLayoutBinding::inflate,
    LoginFragmentViewModel::class.java,
    true
) {
    override fun initFragment(
        binding: FragmentLoginLayoutBinding,
        viewModel: LoginFragmentViewModel?,
        savedInstanceState: Bundle?
    ) {
        viewModel!!.apply {
            binding.viewModel = this
            binding.loginBtn.setOnClickListener {

                if (loginAccount.value == "" || loginPassword.value == "") {
                    Toast.makeText(requireContext(), "账户或密码不能为空", Toast.LENGTH_SHORT)
                        .show()
                } else {
                    loginRequest(loginAccount.value!!, loginPassword.value!!)
                }
            }
        }
    }

    private fun loginRequest(act: String, pwd: String) {
        // 设置登录状态为正在登录
        AppCache.updateStatus(LoginStatus.LOGINING)

        publicViewModel?.apply {
            request(MemberAPI::class.java).login(MemberResponse(act, pwd)).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            withContext(Dispatchers.Main) {
                                Toast.makeText(
                                    requireContext(),
                                    "登录失败，服务器繁忙",
                                    Toast.LENGTH_SHORT
                                ).show()
                                // 设置状态为未登录
                                AppCache.updateStatus(LoginStatus.UNLOGIN)
                                LogUtil.e("${it.errMsg} ${it.errMsg}")
                            }
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            LogUtil.e(it.data.toString())
                            withContext(Dispatchers.Main) {
                                val code = it.data!!.code
                                if (code == 200) {
                                    // 弹出登录成功
                                    Toast.makeText(
                                        requireContext(),
                                        "登录成功",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                    val result = it.data.data
                                    // 将账号信息存入缓存
                                    if (result != null) {
                                        val memberId = result.memberId
                                        val memberName = result.memberName
                                        val jwtToken = result.jwtToken
                                        // 会龄， 头像，身份
                                        val memberAge = result.memberAge
                                        val headPhoto = result.headPhoto
                                        val role = result.role
                                        val memberResponse = MemberResponse(
                                            memberId,
                                            memberName,
                                            memberAge,
                                            headPhoto,
                                            role
                                        )
                                        LogUtil.i(memberResponse.toString())
                                        LogUtil.i(jwtToken)

                                        // 将用户信息存储到SharedPreferences里
                                        spUtil.setItem(SPUtil.MY_LOGIN_INFO, memberResponse.toJson())
                                        spUtil.setItem(SPUtil.MY_TOKEN, jwtToken)
                                        LogUtil.i(" myinfo:${spUtil.getItem(SPUtil.MY_LOGIN_INFO, "").toString()}")
                                        // 将登录的信息放入app内存缓存中，方便非Activity的程序运行，例如Service
                                        AppCache.setMyInfo(memberResponse)
                                        // 存储token
                                        requestBuilder.authorization(jwtToken)

                                        // 设置状态为已登录
                                        AppCache.updateStatus(LoginStatus.LOGINED)
                                        // 登录成功，建立socket
                                        AppCache.getService()
                                            .login() { code: Int, msg: String, aVoid: Void? ->
                                                if (code == 200) {
                                                    Toast.makeText(
                                                        requireContext(),
                                                        "登录成功",
                                                        Toast.LENGTH_SHORT
                                                    ).show()

                                                } else {
                                                    Toast.makeText(
                                                        requireContext(),
                                                        "建立Socket失败 稍后重试",
                                                        Toast.LENGTH_SHORT
                                                    ).show()
                                                }
                                            }

                                        // 查询元素
                                        publicViewModel!!.getCurrentAllMenus()

                                        // 跳转页面
                                        findNavController().navigate(
                                            R.id.mainNavigationFragment,
                                            null,
                                            NavOptions.Builder()
                                                .setPopUpTo(R.id.loginFragment, true)
                                                .build()
                                        )
                                    }
                                } else {
                                    AppCache.updateStatus(LoginStatus.UNLOGIN)
                                    Toast.makeText(
                                        requireContext(),
                                        "登录失败，请检查账号或密码是否正确",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                            }

                        }
                    }
                }
            }
        }
    }
}